<template>
    <view class="bg-white mt-2 pl-[20rpx] pr-[20rpx] pb-[20rpx]">
        <u-form
            labelPosition="left"
            :model="formData"
            :rules="formRules"
            ref="formRef"
        >
            <u-form-item label="性别" prop="sex" borderBottom labelWidth="60">
                <u-input
                    v-model="getSex"
                    disabled
                    disabledColor="#ffffff"
                    placeholder="请选择性别"
                    border="none"
                    @click="showSex = true"
                ></u-input>
                <template #right>
                    <u-icon name="arrow-right"></u-icon>
                </template>
            </u-form-item>
        </u-form>
        <u-action-sheet
            :show="showSex"
            :actions="formData.actions"
            title="请选择性别"
            @close="showSex = false"
            @select="sexSelect"
        >
        </u-action-sheet>
        <view class="submit-btn">
            <u-button type="primary" text="确定" @click="submit"></u-button>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import useUserStore from "@/stores/user";
import { storeToRefs } from "pinia";
import { messageSuccess } from "@/utils/message";
import { useRoute } from "@/hooks/useRoute";
import { getUserInfo, updateSex } from "@/api/user";

const formRef = ref(null);

const userStore = useUserStore();
const { isLogin } = storeToRefs(userStore);

const showSex = ref(false);

const formData = reactive({
    sex: "",
    actions: [
        { name: "男", value: 1 },
        { name: "女", value: 2 },
        { name: "保密", value: 0 },
    ],
});

const formRules = reactive({
    sex: [
        // {
        //     type: "string",
        //     max: 1,
        //     required: true,
        //     message: "请选择男或女",
        //     trigger: ["blur", "change"],
        // },
    ],
});

const getSex = computed(() => {
    let value = "";
    switch (formData.sex) {
        case 1:
            value = "男";
            break;

        case 2:
            value = "女";
            break;

        default:
            value = "未知";
            break;
    }
    return value;
});

const getUserData = async () => {
    if (isLogin.value) {
        const res = await getUserInfo();
        formData.sex = res.sex;
    }
};

const sexSelect = (e) => {
    formData.sex = e.value;
};

const jumpClick = (url) => {
    useRoute().jumpTo({ url: url });
};

const submit = () => {
    formRef.value.validate().then(async (valid) => {
        if (valid) {
            await updateSex({
                sex: formData.sex,
            });
            messageSuccess("修改成功");
        }
    });
};

getUserData();
</script>

<style lang="scss" scoped>
.submit-btn {
    margin-top: 50rpx;
    padding: 0 20rpx;
}
</style>
